/* eslint-disable no-nested-ternary */
/* eslint-disable consistent-return */
/* eslint-disable eqeqeq */
import React, { Fragment } from 'react';
import {
  DownOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Row,
  Col,
  Select,
  Input,
  Button,
  Badge,
  Alert,
  Modal,
  DatePicker,
  Tabs,
  Menu,
  Dropdown,
  Divider,
  message,
  Tooltip,
  Spin,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import { connect } from 'dva';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import downloadFile, { urlParse, formatNumber } from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import SuppContract from '../../components/SuppCont';
import DictCode from '../../components/DictCode';
import NotEnterBillData from './BeforeBill';
import TaskProgress from '../../components/TaskProgress';
import TextOverFlow from '../../components/TextOverFlow';

const { Option } = Select;
const FormItem = Form.Item;

const { MonthPicker } = DatePicker;
const { confirm } = Modal;
const { TabPane } = Tabs;
let uploadFiles = null;

@connect(({ supplybilling, loading }) => ({
  supplybilling,
  data: supplybilling.data,
  formFieldsValue: supplybilling.formFieldsValue,
  loading:
    loading.models.supplybilling &&
    !loading.effects['supplybilling/getProgress'] &&
    !loading.effects['supplybilling/markModelData'] &&
    !loading.effects['supplybilling/uploadFileWithProgress'] &&
    !loading.effects['supplybilling/updateCheckCreate'],
  signLoading: loading.effects['supplybilling/markModelData'], // 标记已收费的loading
  giveBillLoading:
    loading.effects['supplybilling/updateCheckCreate'] ||
    loading.effects['supplybilling/uploadFileWithProgress'], // 生成账单的loading
  expandForm: supplybilling.expandForm,
  respUserList: supplybilling.respUserList,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      SUPP_BILL_STATE: [],
      statusMap: ['', 'default', 'processing', 'warning', 'success'],
      supplyNameList: [], // 签约方数据源
      supplyNameListAll: [], // 添加全部
      selectedRowKeys: [],
      selectedRows: [],
      activeKey: '1',
      sumPrice: 0, // 总钱数

      isSign: false, // 标记完成后确定弹框显隐
      exportLoding: false,
    };
  }

  componentDidMount() {
    this.checkHasTask();
    const { activeKey } = this.state;
    const {
      location: { search },
      data: { pagination },
      form,
      dispatch,
      location,
    } = this.props;
    // 获取所属客服列表数据
    dispatch({
      type: 'supplybilling/fetchRespUserList',
      payload: {},
    });
    dispatch({
      type: 'supplybill/updateModelData',
      payload: {
        formFieldsValue: { defaultFlag: '1' },
        progressPercent: 0,
      },
    });
    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
    form.resetFields(['custIds', 'suppIdModal']);
    const key = urlParse(search).activeKey || activeKey;

    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SUPP_BILL_STATE'],
    })
      .then(data => {
        let taskSourceList = [];
        if (data && data.SUPP_BILL_STATE && data.SUPP_BILL_STATE.length) {
          taskSourceList = data.SUPP_BILL_STATE;
        }
        this.setState({ SUPP_BILL_STATE: taskSourceList });
      })

      .then(() => {
        // 签约方列表
        dispatch({
          type: 'supplybilling/getSuppList',
          payload: {
            status: 2,
          },
          callback: res => {
            if (res.success) {
              const all = { suppId: 'SUPP_ALL', name: '全部' };
              this.setState({
                supplyNameList: res.data,
                supplyNameListAll: [all, ...res.data],
                activeKey: key,
              });
            } else {
              message.warning(`${res.message || '暂无数据！'}`);
            }
          },
        });
      });
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'supplybilling/checkCreateBillTask',
    });
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const {
      data: { pagination },
      dispatch,
    } = this.props;
    if (!flag) {
      dispatch({
        type: 'supplybilling/updateModelData',
        payload: {
          showProgress: false,
        },
      });
      this.getList(pagination.current, pagination.pageSize);
    }
  };

  // 查询表格布局
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'supplybilling/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 获取列表数据
  getList = (nowPage, pageNum, queryParam, isClear = true) => {
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
        sumPrice: 0,
      });
    }
    const { dispatch, form } = this.props;
    const { activeKey } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const tempFieldsValue = queryParam || fieldsValue;
      delete tempFieldsValue.billYmModal;
      delete tempFieldsValue.suppIdModal;
      dispatch({
        type: 'supplybilling/updateModelData',
        payload: { formFieldsValue: tempFieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(tempFieldsValue).forEach(key => {
        if (tempFieldsValue[key] && tempFieldsValue[key].key) {
          formFieldsValue[key] =
            tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
        } else {
          formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
        }
        delete formFieldsValue.operTime;
      });
      const pageArg = {
        currentPage: nowPage,
        pageSize: pageNum,
      };
      formFieldsValue.billYm =
        formFieldsValue && formFieldsValue.billYm && formFieldsValue.billYm.format('YYYYMM');
      const values = {
        ...formFieldsValue,
        pageArg,
      };
      if (activeKey === '2') {
        dispatch({
          type: 'supplybilling/getEnterList',
          payload: values,
        });
      } else {
        dispatch({
          type: 'supplybilling/getListBill',
          payload: values,
        });
      }
    });
  };

  // 标记已收费
  markCharged = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择数据进行操作！');
      return;
    }
    const selectKey = [];
    let billType = null;
    const billNoList = [];
    // eslint-disable-next-line array-callback-return
    selectedRows.map(item => {
      selectKey.push({ billState: item.billState, billNo: item.billNo });
    });
    // eslint-disable-next-line array-callback-return
    selectKey.map(items => {
      if (items.billState === 1) {
        billType = 1;
      } else {
        billType = 2;
        billNoList.push(items.billNo);
      }
    });
    if (billType === 1 && billNoList.length === 0) {
      this.setState({
        isSign: true,
      });
    } else {
      message.warning(` 账单编号${billNoList.length > 1 ? '分别' : ''} 为 ${billNoList.join('、')}
      的账单不允许标记，只能针对状态为“待收费”的账单操作标记收费！`);
      this.setState({
        isSign: false,
      });
    }
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'supplybilling/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ billYm: null });
  };

  // 未进账单
  onRef = ref => {
    this.child = ref;
  };

  // 切换页签
  changeTabPane = activeKey => {
    router.push(`/chargemanage/supplybilling/index?activeKey=${activeKey}`);
    this.setState({ activeKey }, () => {
      if (activeKey === '1') {
        this.setState(
          {
            selectedRows: [],
            selectedRowKeys: [],
            sumPrice: 0,
          },
          () => {
            this.getList(1, 10);
          }
        );
      } else {
        this.child.getList();
      }
    });
  };

  // 切换模态框：新增、修改
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplybilling/updateModelData',
      payload: { modalVisible: !!flag },
    });
  };

  // 提交生成账单数据
  submitData = () => {
    const { dispatch, form } = this.props;
    let submitData = {};
    form.validateFieldsAndScroll(['suppIdModal', 'billYmModal'], (err, values) => {
      if (!err) {
        // eslint-disable-next-line no-restricted-syntax
        for (const key in values) {
          if (values[key] && values[key].key) {
            // eslint-disable-next-line no-param-reassign
            values[key] = values[key].key;
          } else if (key === 'billYmModal') {
            // eslint-disable-next-line no-param-reassign
            values[key] = values[key].format('YYYYMM');
          } else {
            // eslint-disable-next-line no-param-reassign
            values[key] = values[key] ? values[key] : '';
          }
        }
        submitData = { sendSuppId: values.suppIdModal, billYm: values.billYmModal };

        dispatch({
          type: 'supplybilling/updateCheckCreate',
          payload: submitData,
          callback: response => {
            if (response.success && response.data === 0) {
              dispatch({
                type: 'supplybilling/uploadFileWithProgress',
                payload: { batchType: 1, params: submitData },
              });
            } else {
              message.warning('当前签约方已生成过选择月份账单，增量数据请到未进账单页面生成!');
            }
          },
        });
      }
    });
  };

  // 导出数据
  export = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      message.warning('请至少选择一条账单数据');
    } else {
      this.exportExcel(singleOrMerge);
    }
  };

  // 导出excel
  exportExcel = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    const params = {
      billIdList: selectedRowKeys,
    };
    const { dispatch } = this.props;
    this.setState({
      exportLoding: true,
    });
    dispatch({
      type:
        singleOrMerge == 'downSingleBillDet'
          ? 'supplybilling/singleExport'
          : 'supplybilling/mergeExport',
      payload: params,
    }).then(res => {
      if (res.success) {
        uploadFiles = setInterval(() => {
          dispatch({
            type: 'supplybilling/uploadFile',
            payload: { billKey: res.data, downType: singleOrMerge == 'downSingleBillDet' ? 2 : 3 },
          }).then(resFile => {
            if (resFile.success) {
              if (resFile.success && resFile.data && resFile.data.fileId && resFile.data.fileName) {
                window.clearInterval(uploadFiles);
                downloadFile(
                  { fileId: resFile.data.fileId, fileName: resFile.data.fileName },
                  '/csApi/fileServer/downloadFile',
                  'GET',
                  () => {
                    this.setState({
                      exportLoding: false,
                    });
                  }
                );
              }
            } else {
              message.warning(resFile.message || '下载失败');
              window.clearInterval(uploadFiles);
              this.setState({
                exportLoding: false,
              });
            }
          });
        }, 2000);
      } else {
        this.setState({
          exportLoding: false,
        });
        window.clearInterval(uploadFiles);
        message.warning(res.message || '下载失败');
      }
    });
  };

  // 合并账单
  mergeBill = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'supplybilling/checkCreateBillTask',
    }).then(response => {
      if (response.success) {
        if (response.data && response.data.taskCode === 3) {
          message.warning('当前有账单任务正在生成，请稍后操作！');
          return false;
          // eslint-disable-next-line no-else-return
        } else {
          // eslint-disable-next-line no-lonely-if
          if (selectedRowKeys.length >= 2) {
            confirm({
              icon: <QuestionCircleOutlined />,
              title: '你确定要合并吗?',
              okText: '合并',
              okType: 'default',
              cancelText: '取消',
              style: { top: 200 },
              onOk: () => {
                dispatch({
                  type: 'supplybilling/uploadFileWithProgress',
                  payload: { batchType: 2, params: { billIdList: selectedRowKeys } },
                });
              },
              onCancel: () => {
                this.setState({ selectedRowKeys: [], sumPrice: 0 });
              },
            });
          } else {
            message.warning('请至少选择两条账单数据');
          }
        }
      } else {
        message.warning(response.message || '服务端未知错误');
      }
    });
  };

  // 删除账单
  deleteBill = () => {
    const {
      dispatch,
      data: {
        pagination: { current, pageSize, total },
      },
    } = this.props;
    const { selectedRowKeys, selectedRows, SUPP_BILL_STATE } = this.state;
    if (selectedRowKeys.length) {
      const iaDisable = selectedRows.some(row => row.billState !== 1);
      if (iaDisable) {
        const idList = [];
        const filterRows = selectedRows.filter(item => item.billState !== 1);
        filterRows.forEach(r => {
          SUPP_BILL_STATE.forEach(c => {
            if (c.itemCode === `${r.billState}`) {
              idList.push(r.billNo);
            }
          });
        });
        return message.warning(
          `账单编号${idList.length > 1 ? '分别' : ''}为“${idList.join(
            '、'
          )}”的账单不允许删除，只能针对状态为“待收费”的账单操作删除!`
        );
      }
      const billNoList = [];
      selectedRows.forEach(item => {
        billNoList.push(item.billNo);
      });
      confirm({
        icon: <QuestionCircleOutlined />,
        title: `你确定要删除编号为"${billNoList.join('、')}"的账单吗?`,
        content: (
          <div>
            <span>注意：</span>
            <span>
              当月账单全部删除后，需要重新操作生成账单；
              <br />
              <span style={{ opacity: 0 }}>注意：</span>
              当月账单部分删除后，被删除的数据会进入到【未进账单数据】中。
            </span>
          </div>
        ),
        okText: '删除',
        cancelText: '取消',
        width: 570,
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'supplybilling/deleteBill',
            payload: { billIdList: selectedRowKeys },
          }).then(res => {
            if (res.success) {
              const selectedLen = 1;
              if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                this.getList(current - 1, pageSize);
              } else {
                this.getList(current, pageSize);
              }
              this.setState({ selectedRowKeys: [], selectedRows: [], sumPrice: 0 });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败'}`);
            }
          });
        },
        onCancel: () => {
          this.setState({ selectedRowKeys: [], sumPrice: 0 });
        },
      });
    } else {
      message.warning('请至少选择一条账单数据');
    }
    return true;
  };

  // 查询合同
  getDatathree = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 发送财务
  sendFinance = () => {
    message.warning('努力开发中。。。');
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, undefined, false);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    const totalPrice = selectedRows.reduce(
      (total, currentValue) => total + currentValue.billAmo || 0,
      0
    );
    this.setState({ selectedRowKeys, selectedRows, sumPrice: totalPrice });
  };

  // 标记已收费确定
  submark = () => {
    const { selectedRowKeys } = this.state;
    const {
      dispatch,
      data: { pagination },
    } = this.props;
    dispatch({
      type: 'supplybilling/markModelData',
      payload: { billIdList: selectedRowKeys },
      callback: res => {
        if (res.success) {
          if (res.data.errorCount == '0' && res.data.successCount != '0') {
            message.success('标记成功！');
            this.setState({
              selectedRowKeys: [],
              selectedRows: [],
              isSign: false,
              sumPrice: 0,
            });
            this.getList(pagination.current, pagination.pageSize);
          }
        } else {
          this.setState({
            isSign: false,
          });
          message.warning(res.message || '标记失败：服务端未知错误');
        }
      },
    });
  };

  // 标记成功的关闭
  handleCancel = () => {
    const {
      data: { pagination },
    } = this.props;
    this.getList(pagination.current, pagination.pageSize);
  };

  // 关闭标记弹框
  closeUnmark = () => {
    this.setState({
      isSign: false,
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    const { queryParam } = location;
    if (queryParam) {
      await dispatch({
        type: 'supplybilling/updateModelData',
        payload: {
          expandForm: true,
        },
      });
    } else {
      dispatch({
        type: 'supplybilling/updateModelData',
        payload: { expandForm: false },
      });
    }
    await this.resetSearch();
    await this.getList(1, 10, queryParam);
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const {
      supplybilling,
      form: { getFieldDecorator },
      data,
      loading,
      formFieldsValue,
      expandForm,
      signLoading,
      giveBillLoading,
      dispatch,
      respUserList,
    } = this.props;
    const {
      activeKey,
      statusMap,
      sumPrice,
      supplyNameList,
      supplyNameListAll,
      selectedRowKeys,
      isSign,
      selectedRows,
      exportLoding,
    } = this.state;
    // 表单布局
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '账单年月',
        dataIndex: 'billYm',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单编号',
        dataIndex: 'billNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '账单金额',
        dataIndex: 'billAmo',
        align: 'right',
        width: 130,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  涉及人数：
                  {record.involvePersonNum}
                </p>
                <p>
                  {record.agtsrvIns ? `代收社保：${formatNumber(record.agtsrvIns)}` : ''}
                </p>
                <p>
                  {record.agtsrvAccu ? `代收公积金：${formatNumber(record.agtsrvAccu)}` :''}
                </p>
                <p>
                  {record.agtsrvWage ? `代收工资：${formatNumber(record.agtsrvWage)}` : ''}
                </p>
                <p>
                  {record.othCost ? `服务费：${formatNumber(record.othCost)}` : ''}
                </p>
                <p>
                  {record.bnftAmo ? `福利费：${formatNumber(record.bnftAmo)}` : ''}
                </p>
                <p>
                  {record.medExamAmo ? `体检费：${formatNumber(record.medExamAmo)}` : ''}
                </p>
                <p>
                  {record.cmpinsAmo ? `保险：${formatNumber(record.cmpinsAmo)}` : ''}
                </p>
                <p>
                  {record.riskAmo ? `风险金：${formatNumber(record.riskAmo)}` : ''}
                </p>
              </div>
            }
          >
            {/* <span>{text ? `${text.toFixed(2)}...` : text === 0 ? 0 : '--'}</span> */}

            {text ? (
              <span>
                {formatNumber(text)}
                <EllipsisOutlined style={{ fontSize: 14, color: '#08c' }} />
              </span>
            ) : (
              <span> {text === 0 ? 0 : '--'}</span>
            )}
          </Tooltip>
        ),
      },

      {
        title: '供应商合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单状态',
        dataIndex: 'billState',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (val, record) => <Badge status={statusMap[val]} text={record.billStateName} />,
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        align: 'left',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '操作',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <a
              onClick={() =>
                router.push(`/chargemanage/supplybilling/detail?billId=${record.billId}`)
              }
            >
              查看
            </a>
            {record.billState === 1 && record.involvePersonNum > 1 ? (
              <Authorized authority="cs:nsBill:split" noMatch={null}>
                <Divider type="vertical" />
                <a
                  onClick={() =>
                    router.push(`/chargemanage/supplybilling/split?billId=${record.billId}`)
                  }
                >
                  拆分
                </a>
              </Authorized>
            ) : null}
          </div>
        ),
      },
    ];

    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: '生成账单',
      visible: supplybilling.modalVisible,
      confirmLoading: giveBillLoading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: () => {
        this.handleModalVisible(false);
      },
      destroyOnClose: true,
    };
    const billingDownload = (
      <Menu>
        {checkPermissions('cs:nsBill:downBillDet') && (
          <Menu.Item onClick={() => this.export('downSingleBillDet')}>单个下载</Menu.Item>
        )}
        {checkPermissions('cs:nsBill:downBill') && (
          <Menu.Item onClick={() => this.export('downMergeBillDet')}>合并下载</Menu.Item>
        )}
      </Menu>
    );
    const moreMenu = (
      <Menu>
        {checkPermissions('cs:nsBill:merge') && (
          <Menu.Item onClick={this.mergeBill}>合并</Menu.Item>
        )}

        {checkPermissions('cs:nsBill:deleteBill') && (
          <Menu.Item onClick={this.deleteBill}>删除</Menu.Item>
        )}
        {checkPermissions('cs:nsBill:updateChrgState') && (
          <Menu.Item onClick={this.markCharged}>标记已收费</Menu.Item>
        )}
      </Menu>
    );
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  allowClear
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {supplyNameList.map(options => (
                    <Option key={options.suppId} title={options.name}>
                      {options.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="供应商合同">
              {getFieldDecorator('contId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.contId,
              })(<SuppContract getData={this.getDatathree} allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.getList(1, 10)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
    const renderAdvancedForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  allowClear
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {supplyNameList.map(options => (
                    <Option key={options.suppId} title={options.name}>
                      {options.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="供应商合同">
              {getFieldDecorator('contId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.contId,
              })(<SuppContract getData={this.getDatathree} allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="账单年月">
              {getFieldDecorator('billYm', {
                initialValue: formFieldsValue.billYm,
              })(<MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem {...formItemLayout} label="账单状态">
                {getFieldDecorator('billState', {
                  initialValue: formFieldsValue.billState,
                })(<DictCode dictType="SUPP_BILL_STATE" />)}
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem {...formItemLayout} label="账单编号">
                {getFieldDecorator('billNo', {
                  rules: [{ required: false }],
                  initialValue: formFieldsValue.billNo,
                })(<Input placeholder="请输入账单编号" />)}
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem label="所属客服" {...formItemLayout}>
                {getFieldDecorator('primId', {
                  rules: [{ required: false, message: '请选择' }],
                  initialValue: formFieldsValue.primId,
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    showSearch
                    optionFilterProp="children"
                    allowClear
                  >
                    {respUserList.map(item => (
                      <Option key={item.userId} title={item.userName}>
                        {item.userName}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.getList(1, 10)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
    const renderForm = expandForm ? renderAdvancedForm : renderSimpleForm;
    return (
      <PageHeaderWrapper>
        <Spin spinning={exportLoding || loading}>
          <Card className={styles.tabCard}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              <TabPane tab="账单" key="1">
                <div
                  className={styles.tableListForm}
                  style={{
                    // margintop: 4,
                    marginBottom: 16,
                    // paddingTop: 16,
                    // paddingRight: 16,
                    padding: '24px 24px 0 0',
                    backgroundColor: '#fafafa',
                  }}
                >
                  {renderForm}
                </div>
                <Row>
                  <Authorized authority="cs:nsBill:createBill" noMatch={null}>
                    <Button type="primary" onClick={() => this.handleModalVisible(true)}>
                      生成账单
                    </Button>
                  </Authorized>
                  <Dropdown overlay={billingDownload}>
                    <Button style={{ marginLeft: 8 }}>账单下载</Button>
                  </Dropdown>
                  <Dropdown overlay={moreMenu}>
                    <Button style={{ marginLeft: 8 }}>
                      更多 <DownOutlined />
                    </Button>
                  </Dropdown>
                </Row>
                {supplybilling.isHasTask ? (
                  <Alert
                    style={{ margin: '16px 0 15px 0' }}
                    message={
                      <span>
                        您有正在生成账单的任务
                        <a
                          style={{ marginLeft: 20 }}
                          onClick={() => {
                            dispatch({
                              type: 'supplybilling/updateModelData',
                              payload: {
                                showProgress: true,
                              },
                            });
                          }}
                        >
                          查看
                        </a>
                      </span>
                    }
                    type="warning"
                    showIcon
                  />
                ) : (
                  <Alert
                    style={{ margin: '16px 0 15px 0' }}
                    message={
                      <Fragment>
                        已选择 <span style={{ color: '#088FEA' }}> {selectedRowKeys.length} </span>
                        项 &nbsp; 总计： &nbsp;
                        <span style={{ fontWeight: 'bold' }}>
                          {sumPrice ? sumPrice.toFixed(2) : 0}
                        </span>
                        &nbsp;元
                      </Fragment>
                    }
                    type="info"
                    showIcon
                  />
                )}
                <StandardTable
                  selectedRows={selectedRows}
                  selectedRowKeys={selectedRowKeys}
                  data={data}
                  rowKey="billId"
                  columns={columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
                {/* 生产账单 */}
                <Modal {...modalConfig}>
                  <Form>
                    <FormItem
                      {...formItemLayoutModal}
                      label={
                        <Tooltip title="可以选择全部，也可输入签约方生成账单">
                          签约方 <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                        </Tooltip>
                      }
                    >
                      {getFieldDecorator('suppIdModal', {
                        rules: [{ required: supplybilling.modalVisible, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请输入关键字检索"
                          labelInValue
                          showSearch
                          optionFilterProp="children"
                        >
                          {supplyNameListAll.map(options => (
                            <Option key={options.suppId}>{options.name}</Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                    <FormItem label="截止年月" {...formItemLayoutModal}>
                      {getFieldDecorator('billYmModal', {
                        rules: [{ required: supplybilling.modalVisible, message: '请选择' }],
                        initialValue: moment(),
                      })(
                        <MonthPicker
                          placeholder="请选择"
                          disabledDate={current =>
                            current < moment().subtract(1, 'months') ||
                            current > moment().add(5, 'months')
                          }
                          style={{ width: '100%' }}
                        />
                      )}
                    </FormItem>
                  </Form>
                </Modal>
                <TaskProgress
                  progressVisible={supplybilling.showProgress}
                  progressPercent={supplybilling.progressPercent || 0}
                  isShowResult={supplybilling.progressPercent === 100}
                  resultInfo={supplybilling.resultInfo}
                  checkHasTask={this.checkHasTask}
                  handleProgressModalVisible={this.handleProgressModalVisible}
                />
              </TabPane>
              <TabPane tab="未进账单数据" key="2">
                <div
                  className={styles.tableListForm}
                  style={{
                    marginBottom: 16,
                    padding: '24px 24px 0 0',
                    backgroundColor: '#fafafa',
                  }}
                >
                  {renderForm}
                </div>
                <NotEnterBillData value={activeKey} onRef={this.onRef} />
              </TabPane>
            </Tabs>
          </Card>
        </Spin>
        <Modal
          visible={isSign}
          onOk={this.submark}
          onCancel={this.closeUnmark}
          closable={false}
          destroyOnClose
          width="450px"
          footer={[
            <Button key="back" onClick={this.closeUnmark}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={this.submark} loading={signLoading}>
              确认
            </Button>,
          ]}
        >
          <div style={{ margin: '15px 15px 0 15px' }}>
            <ExclamationCircleOutlined
              style={{ fontWeight: 800, color: '#EEC900', fontSize: '20px' }}
            />
            <span style={{ fontSize: '18px', fontWeight: 800, margin: '20px 0 0 10px' }}>
              已选择{selectedRowKeys.length}条数据，是否确认全部标记已收费
            </span>
            <p style={{ color: '#A19095', margin: '10px 0 0 28px' }}>
              请线下和财务核实每笔费用款已到款，标记后不可取消标记。
            </p>
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
